<template>
  <div class="component-upload-image">
    <!-- 文件上传组件 -->
    <el-upload
        multiple
        :action="uploadImgUrl"
        list-type="picture-card"
        :on-success="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        name="file"
        :on-remove="handleRemove"
        :show-file-list="true"
        :headers="headers"
        :file-list="fileList"
        :on-preview="openZoomDialog"
        :class="{ hide: fileList.length >= limit }"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <!-- 裁剪对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="裁剪图片" width="800px" append-to-body>
      <ImageCropper :imageSrc="currentImageUrl" @cropped="handleCropped" />
    </el-dialog>

    <!-- 放大图片对话框 -->
    <el-dialog :visible.sync="zoomDialogVisible" title="查看图片" append-to-body>
      <div style="text-align:center;">
        <image-preview v-if="zoomedImageUrl" :src="zoomedImageUrl" :width="150" :height="150"></image-preview>
      </div>
    </el-dialog>

    <!-- 上传提示 -->
    <div v-if="showTip" class="el-upload__tip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import ImageCropper from './ImageCropper.vue';
import axios from 'axios';

export default {
  components: {
    ImageCropper,
    'image-preview': () => import('@/components/ImagePreview') // 假设 ImagePreview 是一个自定义组件，请根据实际情况调整路径
  },
  props: {
    value: [String, Object, Array],
    limit: {
      type: Number,
      default: 5,
    },
    fileSize: {
      type: Number,
      default: 5,
    },
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/uploadMinio",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      dialogVisible: false,
      currentImageUrl: '',
      zoomDialogVisible: false,
      zoomedImageUrl: null
    };
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          const list = Array.isArray(val) ? val : this.value.split(',');
          this.fileList = list.map(item => ({ name: item, url: item }));
        } else {
          this.fileList = [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    openZoomDialog(file) {
      this.zoomedImageUrl = file.url;
      this.zoomDialogVisible = true;
    },
    handleCropped(croppedImageUrl) {
      fetch(croppedImageUrl).then(res => res.blob()).then(blob => {
        const formData = new FormData();
        formData.append('file', blob, 'cropped-image.png');
        axios.post(this.uploadImgUrl, formData, {
          headers: this.headers
        }).then(response => {
          if (response.data.code === 200) {
            const newImageUrl = response.data.url;
            this.fileList.push({ name: newImageUrl, url: newImageUrl });
            this.$emit("input", this.listToString(this.fileList));
            this.currentImageUrl = newImageUrl;
          } else {
            this.$modal.msgError(response.data.msg);
          }
        }).catch(error => {
          this.$modal.msgError("上传图片失败，请重试");
        }).finally(() => {
          this.dialogVisible = false;
        });
      });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.$emit("input", this.listToString(this.fileList));

      if (this.currentImageUrl === file.url) {
        this.currentImageUrl = null;
      }
    },
    handleUploadSuccess(response) {
      if (response.code === 200) {
        const newImageUrl = response.data.url;
        this.fileList.push({ name: newImageUrl, url: newImageUrl });
        this.$emit("input", this.listToString(this.fileList));
      } else {
        this.$modal.msgError(response.msg);
      }
    },
    handleBeforeUpload(file) {

      if (!this.checkFileType(file) || !this.checkFileSize(file)) {
        return false;
      }
      this.currentImageUrl = URL.createObjectURL(file);
      this.dialogVisible = true;

      return false; // 阻止默认上传
    },
    checkFileType(file) {
      let isImg = this.fileType.some(type => file.type.indexOf(type) > -1 || file.name.toLowerCase().endsWith(`.${type}`));
      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
      }
      return isImg;
    },
    checkFileSize(file) {
      const isLt = file.size / 1024 / 1024 < this.fileSize;
      if (!isLt) {
        this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
      }
      return isLt;
    },
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
    },
    listToString(list, separator = ",") {
      return list.map(item => item.url).join(separator);
    }
  }
};
</script>

<style scoped>
.component-upload-image .el-upload.hide {
  display: none !important;
}
</style>
